<?php

namespace Biz\model;


use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\ImgUrl;

class ShopCategoryClassify extends BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'shop_category_classify';

    const STATUS_NORMAL = 1;
    const STATUS_DELETE = 0;
    const STATUS_HIDE = 2;//不显示

    const DEEP_FIRST_CLASSIFY = 1;
    const DEEP_SECOND_CLASSIFY = 2;
    const DEEP_THIRD_CLAORCATE = 3;
    const DEEP_FOUR_CATEGORY = 4;

    const DEEP_CLASSIFY_DISPALY = [
        self::DEEP_FIRST_CLASSIFY => '一',
        self::DEEP_SECOND_CLASSIFY => '二',
        self::DEEP_THIRD_CLAORCATE => '三',
        self::DEEP_FOUR_CATEGORY => '四',
    ];

    const PAGESIZE = 20;

    const SORT_MAX = 1000;


    public static function addData($data = [])
    {
        $data['status'] = self::STATUS_NORMAL;
        $data['addtime'] = date("Y-m-d H:i:s");
        $data['edittime'] = date("Y-m-d H:i:s");

        self::insert($data);

        return self::id();
    }

    public static function getInfoByName($classifyName)
    {
        if ($classifyName) {
            return self::get("*", [
                'parent_id' => 0,
                'classify_name' => $classifyName,
                'status' => self::STATUS_NORMAL,
            ]);
        }

    }

    public static function getInfo($id, $status = null)
    {
        $where = [
            'id' => $id,
            'status' => self::STATUS_NORMAL,
        ];
        if (!is_null($status)) {
            $where['status'] = $status;
        }
        $info = self::get("*", $where);
        self::format($info);

        return $info;
    }

    private static function format(&$info)
    {
        if ($info) {
            foreach ($info as $key => $value) {
                switch ($key) {
                    case 'icon':
                        $info['icon_url'] = $value ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $value,
                            ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                        break;
                }
            }
        }
    }

    public static function selectClassifyByPids(
        $parent_ids,
        $status = [
            self::STATUS_NORMAL,
            self::STATUS_HIDE,
        ],
        $order = null
    ) {
        $where['parent_id'] = $parent_ids;
        if (!is_null($status)) {
            $where['status'] = $status;
        }
        if (!is_null($order)) {
            $where['ORDER'] = $order;
        }
        $cateInfos = self::selectInfos($where);

        $rst = [];
        foreach ($cateInfos as $cateInfo) {
            $rst[$cateInfo['parent_id']][] = [
                'id' => $cateInfo['id'],
                'classify_name' => $cateInfo['classify_name'],
                'status' => $cateInfo['status'],
                'deep' => $cateInfo['deep'],
                'sort' => $cateInfo['sort'],
                'icon' => $cateInfo['icon'],
                'icon_url' => $cateInfo['icon_url'],
            ];
        }

        return $rst;

    }

    public static function selectInfos($where = [], $field = '*', $format = true)
    {
        if (!isset($where['status'])) {
            $where['status'] = self::STATUS_NORMAL;
        }

        $list = [];
        $result = self::select($field, $where);
        if ($format) {
            foreach ($result as $info) {
                self::format($info);
                $list[] = $info;
            }

            return $list;
        } else {
            return $result;
        }
    }

    public static function saveCate($currCateIds, $parent_id, $admin_id)
    {
        $currCateIds = array_values($currCateIds);
        self::updateClassify([
            'status' => self::STATUS_NORMAL,
        ], [
            'parent_id' => $parent_id,
            'cate_id' => $currCateIds,
            'status' => self::STATUS_DELETE,
        ]);

        self::updateClassify([
            'status' => self::STATUS_DELETE,
        ], [
            'parent_id' => $parent_id,
            'cate_id[!]' => $currCateIds,
            'status' => self::STATUS_NORMAL,
        ]);


        $cateIds = self::selectCateIdByPids($parent_id);
        $cateIds = $cateIds ? $cateIds[$parent_id] : [];

        $addIds = array_diff($currCateIds, $cateIds);

        $addInfos = array_map(function ($addid) use ($parent_id, $admin_id) {
            return [
                'parent_id' => $parent_id,
                'cate_id' => $addid,
                'admin_id' => $admin_id,
            ];
        }, $addIds);

        if ($addInfos) {
            self::addMutiData(array_values($addInfos));
        }

    }

    public static function updateClassify($data = [], $where = [])
    {
        return self::update($data, $where);

    }

    public static function selectCateIdByPids($parent_ids)
    {
        $cateInfos = self::selectInfos([
            'parent_id' => $parent_ids,
        ]);

        $rst = [];
        foreach ($cateInfos as $cateInfo) {
            $rst[$cateInfo['parent_id']][] = $cateInfo['cate_id'];
        }

        return $rst;
    }

    public static function addMutiData($datas = [])
    {

        $datas = array_map(function ($data) {

            $data['status'] = self::STATUS_NORMAL;
            $data['addtime'] = date("Y-m-d H:i:s");
            $data['edittime'] = date("Y-m-d H:i:s");

            return $data;
        }, $datas);

        return self::insert($datas);
    }

    public static function delClassify($id, $action_uid)
    {
        self::updateClassify([
            'status' => self::STATUS_DELETE,
            'admin_id' => $action_uid,
        ], ['id' => $id]);
        self::updateClassify([
            'status' => self::STATUS_DELETE,
            'admin_id' => $action_uid,
        ], ['parent_id' => $id]);
    }

    public static function getClassifyByPids(
        $parentIds,
        $status = [
            self::STATUS_NORMAL,
            self::STATUS_HIDE,
        ]
    ) {
        $infos = self::select("*", [
            'parent_id' => $parentIds,
            'status' => $status,
            'ORDER' => ['sort' => 'DESC'],
        ]);
        $rst = [];
        foreach ($infos as $info) {
            $rst[$info['parent_id']][] = $info;
        }

        return $rst;
    }

    public static function getListByIds(
        $ids,
        $status = [
            self::STATUS_NORMAL,
            self::STATUS_HIDE,
        ]
    ) {
        $infos = self::select('*', [
            'id' => $ids,
            'status' => $status,
            'ORDER' => ['sort' => 'DESC'],
        ]);

        return array_column($infos, null, 'id');
    }

    public static function admAddClassify($data)
    {
        $data['addtime'] = date('Y-m-d H:i:s');
        $data['edittime'] = date('Y-m-d H:i:s');
        $data['status'] = isset($data['status']) ? $data['status'] : self::STATUS_HIDE;
        self::insert($data);

        return self::id();
    }

    public static function admSaveClassify($data, $classifyId)
    {
        self::update($data, ['id' => $classifyId]);
    }

    public static function admSortClassify($sortInfo)
    {
        foreach ($sortInfo as $moduleId => $sort) {
            self::update(['sort' => self::SORT_MAX - $sort], ['id' => $moduleId]);
        }
    }


    public static function getBasicInfoByAdmin($param, $field = 'classify_name')
    {
        $categoryId = array_values($param);
        $categoryName = self::select($field, ['id' => $categoryId]);

        return implode('——', $categoryName);
    }

    // cache查询方法，不限制状态查询，否则会缓存穿透
    public static function getCategoryInfo($categoryId)
    {
        return self::select('*', ['id' => $categoryId]);
    }

    public static function getList($where = [], $field = '*')
    {
        return self::select($field, $where);
    }

    public static function selectNormalIdByPids($parent_ids, $status = [], $has_cate = false)
    {
        $where['parent_id'] = $parent_ids;
        if ($status && is_array($status)) {
            $where['status'] = $status;
        }
        if ($has_cate) {
            $where['cate_id[!]'] = 0;
        }
        $cateInfos = self::selectInfos($where);

        $rst = [];
        foreach ($cateInfos as $cateInfo) {
            if (!$has_cate) {
                $rst[$cateInfo['parent_id']][] = $cateInfo['id'];
            } else {
                $rst[] = $cateInfo['cate_id'];
            }

        }

        return $rst;
    }

    /**
     * 获取一级分类
     */
    public static function getFirstDeepClassify()
    {
        $field = ['id', 'classify_name(title)'];
        $where = [
            'status' => ShopCategoryClassify::STATUS_NORMAL,
            'deep' => ShopCategoryClassify::DEEP_FIRST_CLASSIFY,
            'ORDER' => ['sort' => 'DESC'],
        ];

        return ShopCategoryClassify::select($field, $where) ?? [];
    }

    /**
     * @param $where
     * @param string $field
     * @return array
     */
    public static function selectByWhere($where, $field = '*')
    {
        return self::select($field, $where);
    }

}
